package com.cxs.drawpointdemo.util;

import ohos.app.Context;
import ohos.data.distributed.common.*;
import ohos.data.distributed.user.SingleKvStore;

public class KvStoreUtils {

    private final static String STORE_ID = "draw_point";
    private static KvManager manager = null;
    private static SingleKvStore kvStore = null;
    private static Context context;

    private KvStoreUtils () {}

    public static void setContext(Context context) {
        KvStoreUtils.context = context;
    }

    /**
     * 创建分布式数据库管理器实例KvManager
     * @return
     */
    public static KvManager getManager() {
        if (manager != null) {
            return manager;
        }
        try {
            // 根据应用上下文创建KvManagerConfig对象
            KvManagerConfig config = new KvManagerConfig(context);
            // 创建分布式数据库管理器实例
            manager = KvManagerFactory.getInstance().createKvManager(config);
        } catch (KvStoreException e) {
            System.out.println(e.getMessage());
        }
        return manager;
    }

    /**
     * 创建SINGLE_VERSION分布式数据库
     * @return
     */
    public static SingleKvStore getKvStore() {
        if (kvStore != null) {
            return kvStore;
        }
        try {
            // 数据库配置
            Options options = new Options();
            options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);
            // 通过分布式数据库管理器实例获取数据库
            kvStore = getManager().getKvStore(options, STORE_ID);
        } catch (KvStoreException e) {
            System.out.println(e.getMessage());
        }
        return kvStore;
    }

}
